package io.openkunlun.javadsl.client;

import com.google.protobuf.ByteString;
import io.openkunlun.javadsl.serialization.DaprSerializer;
import io.openkunlun.javadsl.v1.DaprProtos;
import lombok.Builder;
import lombok.Data;

import java.util.Map;

@Data
@Builder
public final class InvokeBindingAction<T> implements DaprAction<InvokeBindingResult<T>> {

    private String name;
    private Object data;
    private String operation;
    private Map<String, String> metadata;
    private DaprSerializer daprSerializer;
    private Class<T> clazz;

    /**
     * @param daprClient
     * @return
     */
    @Override
    public InvokeBindingResult<T> invoke(DaprClient daprClient) throws Exception {
        DaprProtos.InvokeBindingRequest request = DaprProtos.InvokeBindingRequest
                .newBuilder()
                .setName(name)
                .setData(ByteString.copyFrom(daprSerializer.serialize(data)))
                .setOperation(operation)
                .putAllMetadata(metadata)
                .build();

        DaprProtos.InvokeBindingResponse response = daprClient.invokeBinding(request);
        return new InvokeBindingResult<>(daprSerializer.deserialize(response.getData().toByteArray(), clazz), response.getMetadataMap());
    }
}
